<?php
/**
 * Created by PhpStorm.
 * User: Frings
 * Date: 2016/10/31
 * Time: 16:21
 */

namespace app\models;

use app\librarys\DbCacheUtility;
use app\librarys\Inteface;
use app\librarys\Tools;

Class InstitutionUpdateRecord
{

    /**
     * 是否包含机构修改记录
     * @param $institution_code
     * @param $type 1--机构商品池 2--商品分类 3--扩展分类 4--特价活动 5--广告设置 6--广告分类
     * @return bool
     */
    public static function existRecord($institution_code, $type)
    {
        $sql = 'SELECT count(1) FROM t_institution_update_record WHERE institution_code = :institution_code AND Type = :type';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':institution_code', $institution_code);
        $cmd->bindValue(':type', $type);

        $result = $cmd->queryScalar();
        if ($result > 0) {
            return true;
        }
        return false;
    }

    /**
     * 添加机构修改记录
     * @param $institution_code
     * @param $type
     * @return bool
     */
    public static function addRecord($institution_code, $type)
    {
        $id = Tools::db_uuid();
        $sql = 'INSERT INTO t_institution_update_record(id,institution_code,type,create_datetime)
                VALUES (:id,:institution_code,:type,now())';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':id', $id);
        $cmd->bindValue(':institution_code', $institution_code);
        $cmd->bindValue(':type', $type);

        $result = $cmd->execute();
        return $result > 0;
    }


    /**
     * 获取当前机构下属机构
     * @param $institution_code
     * @return array
     */
    public static function getUnderInstitutions($institution_code, $type)
    {
        $sql = 'SELECT t1.* FROM t_institution t1 
                  WHERE t1.is_enabled = 1 
                    AND t1.parent_code = :code 
                    AND NOT exists(SELECT 1 FROM t_institution_update_record t2 WHERE t2.institution_code = t1.code AND t2.type = :type)';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':code', $institution_code);
        $cmd->bindValue(':type', $type);
        $result = $cmd->queryAll();
        return $result;
    }

    public static function getHasModifiedInstitutionCodeList($type)
    {
        $sql = 'SELECT institution_code FROM t_institution_update_record WHERE type=:type';
        $cmd = \Yii::$app->db->createCommand($sql);
        $cmd->bindValue(':type', $type);
        $result = $cmd->queryColumn();
        return $result;
    }
}